import {reqGetVerificationCode, reqCompleteRegister, reqLogin, reqGetUserInfo, reqExitLogin} from "@/api";
import {setUserToken, removeUserToken} from '@/utils/user_token'
//Home模块
const state = {
    verificationCode: '',
    userInfo: {}
}

const actions = {
    async getVerificationCode({commit}, phoneNumber) {
        let result = await reqGetVerificationCode(phoneNumber)
        if (result.code === 200) {
            commit('GETVERIFICATIONCODE', result.data)
            return 'success'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    async completeRegister({commit}, data) {
        let result = await reqCompleteRegister(data)
        if (result.code === 200) {
            return 'success'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    async login({commit}, data) {
        let result = await reqLogin(data)
        if (result.code === 200) {
            commit('LOGIN', result.data.token)
            return 'success'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    async getUserInfo({commit}) {
        let result = await reqGetUserInfo()
        if (result.code === 200) {
            commit('GETUSERINFO', result.data)
            return 'success'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    async exitLogin({commit}) {
        let result = await reqExitLogin()
        if (result.code === 200) {
            commit('EXITLOGIN')
            return 'success'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
}

const mutations = {
    GETVERIFICATIONCODE(state, verificationCode) {
        state.verificationCode = verificationCode
    },
    LOGIN(state, token) {
        setUserToken(token)
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    EXITLOGIN(state) {
        state.userInfo = {}
        removeUserToken()
    },
}

const getters = {}//为了简化仓库中的数据

export default {
    namespaced: true,
    state,
    actions,
    mutations,
    getters
}

